package com.lyz.services;

import com.lyz.models.Session;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public abstract class SessionService<T> {

    @Autowired
    private HttpServletResponse httpServletResponse;

    @Autowired
    private HttpServletRequest httpServletRequest;

    // 1. 生产登录 session
    public final Session<T> login(T userInfo) {
        Session<T> session = new Session<>(userInfo);
        this.saveSession(session);
        Cookie cookie = new Cookie("JSESSIONID", session.getSessionId().toString());
        cookie.setPath("/");
        httpServletResponse.addCookie(cookie);
        return session;
    }

    // 2. 查询 session
    public final Session<T> getSession() {
        Cookie[] cookies = httpServletRequest.getCookies();
        String jsessionid = Stream.of(cookies)
                .collect(Collectors.toMap(Cookie::getName, Cookie::getValue))
                .get("JSESSIONID");
        return findSession(jsessionid);
    }

    // 3. 移除 session
    public final void logout(Object sessionId) {
        this.removeSession(sessionId);
    }

    // 接口

    // 1. 持久化 session
    public abstract void saveSession(Session<T> session);

    // 2. 根据 sessionId 查询 session
    protected abstract Session<T> findSession(Object sessionId);

    // 3. 根据 sessionId 删除 session
    protected abstract void removeSession(Object sessionId);

    // 4. 鉴权
    public abstract boolean check(String permission);

}
